package com.crane.oss.common.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.QuerySendDetailsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.QuerySendDetailsResponse;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.crane.common.framework.utils.DateUtil;
import com.crane.oss.common.bean.request.SendSMSRequest;
import com.crane.oss.common.bean.resp.SendSMSResp;
import com.crane.oss.properties.SmsConfigProperties;
import com.crane.oss.common.service.AliyunSMSService;

import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class AliyunSMSServiceImpl implements AliyunSMSService {
	/**
	 * 短信API服务产品名称
	 */
	protected static final String product = "Dysmsapi";
	/**
	 * 短信API服务产品域名
	 */
	protected static final String domain = "dysmsapi.aliyuncs.com";

	protected static final String regionId = "cn-hangzhou";

    @Autowired
    protected SmsConfigProperties smsConfigProperties;

	@Override
	public SendSMSResp sendSms(SendSMSRequest sendSMSRequest) {
		log.info("--->sendSms request={}", sendSMSRequest);
		SendSMSResp resp = null;
		try {
			List<SendSMSRequest> sendRequestList = new ArrayList<SendSMSRequest>();
			sendRequestList.add(sendSMSRequest);
			List<SendSMSResp> respList = this.sendSms(sendRequestList);
			if (respList.size() > 0) resp = respList.get(0);
		} catch (Exception e) {
			log.info("--->sendSms exception={}", e);
		}
		return resp;
	}

	@Override
	public List<SendSMSResp> sendSms(List<SendSMSRequest> sendRequestList) {
		log.info("--->sendSms list request={}", sendRequestList);
		List<SendSMSResp> respList = new ArrayList<SendSMSResp>();
		try {
	        IClientProfile profile = DefaultProfile.getProfile(regionId, smsConfigProperties.getAccessKeyId(), smsConfigProperties.getAccessKeySecret());
	        DefaultProfile.addEndpoint(regionId, regionId, product, domain);
	        IAcsClient acsClient = new DefaultAcsClient(profile);

	        for (SendSMSRequest sendRequest : sendRequestList) {
		        SendSMSResp resp = new SendSMSResp();
	        	resp.setPhoneNumber(sendRequest.getPhoneNumber());
	        	resp.setMsgTypeNo(sendRequest.getMsgTypeNo());

		        SendSmsRequest request = new SendSmsRequest();
		        request.setMethod(MethodType.POST);
		        request.setPhoneNumbers(sendRequest.getPhoneNumber());
		        request.setSignName(smsConfigProperties.getSignName());
		        request.setTemplateCode(sendRequest.getMsgTypeNo());

		        if (smsConfigProperties.getVerifyCodeTemplate().equals(sendRequest.getMsgTypeNo())) {
		        	//尊敬的用户，您的校验码为：${code}，请勿泄漏于他人！
		        	request.setTemplateParam("{\"code\":"+"\""+sendRequest.getCode()+"\""+"}");

		        	resp.setDynamicCode(sendRequest.getCode());
		        }
		        if (smsConfigProperties.getQuotnNoticeTemplate().equals(sendRequest.getMsgTypeNo())) {
		        	//尊敬的${name}, 您已报价成功。工单号：${code}，请您及时处理。
		        	request.setTemplateParam("{\"name\":"+"\""+sendRequest.getName()+"\""+","+"\"code\":"+"\""+sendRequest.getCode()+"\""+"}");
		        }
		        if (smsConfigProperties.getAssignNoticeTemplate().equals(sendRequest.getMsgTypeNo())) {
		        	//尊敬的${name}，您有新的工单，工单号：${code}，请您及时处理。
		        	request.setTemplateParam("{\"name\":"+"\""+sendRequest.getName()+"\""+","+"\"code\":"+"\""+sendRequest.getCode()+"\""+"}");
		        }

		        SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
		        log.info("--->sendSms phone={}, response={}", sendRequest.getPhoneNumber(), sendSmsResponse);

		        //代表请求成功
		        if(sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK")) {
		        	//发送回执ID
		        	resp.setBizId(sendSmsResponse.getBizId());
		        	resp.setResultCode(sendSmsResponse.getCode());
		        	resp.setMessage(sendSmsResponse.getMessage());

		        	respList.add(resp);
		        }
	        }
		} catch (Exception e) {
            log.info("--->sendSms list exception={}", e);
		}
		return respList;
	}

	@Override
	public void querySmsTemplate() {
		// TODO Auto-generated method stub

	}

	@Override
	public SendSMSResp querySendDetails(String phoneNumber, String bizId, String sendDate) {
		SendSMSResp resp = null;
		try {
	        IClientProfile profile = DefaultProfile.getProfile(regionId, smsConfigProperties.getAccessKeyId(), smsConfigProperties.getAccessKeySecret());
	        DefaultProfile.addEndpoint(regionId, regionId, product, domain);
	        IAcsClient acsClient = new DefaultAcsClient(profile);

	        QuerySendDetailsRequest request = new QuerySendDetailsRequest();
	        request.setPhoneNumber(phoneNumber);
	        request.setBizId(bizId);
	        request.setSendDate(sendDate);
	        request.setPageSize(10L);
	        request.setCurrentPage(1L);

	        QuerySendDetailsResponse querySendDetailsResponse = acsClient.getAcsResponse(request);
        	//代表请求成功
	        if(querySendDetailsResponse.getCode() != null && querySendDetailsResponse.getCode().equals("OK")) {
	        	//1：等待回执，2：发送失败，3：发送成功
	        	String status = querySendDetailsResponse.getSmsSendDetailDTOs().get(0).getSendStatus().toString();
	        	//运营商短信错误码
	        	String errCode = querySendDetailsResponse.getSmsSendDetailDTOs().get(0).getErrCode();

	        	resp = new SendSMSResp();
	        	resp.setBizId(bizId);
	        	resp.setErrCode(errCode);
	        	resp.setStatus(status);
	        	resp.setPhoneNumber(phoneNumber);
	        }
		} catch (Exception e) {
			log.info(" querySendDetails e={}", e);
		}
		return resp;
	}

	public static void main(String[] args) {
        try {
        	DefaultProfile profile = DefaultProfile.getProfile(regionId, "LTAI4GCyeVnEH91cQwkFFEyE", "kiDbFZPLsfCS87pTIdfvIEQBuPOdPT");
			IAcsClient client = new DefaultAcsClient(profile);

			CommonRequest request = new CommonRequest();
	        request.setMethod(MethodType.POST);
	        request.setDomain(domain);
	        request.setVersion("2017-05-25");
	        request.setAction("QuerySmsTemplate");
	        request.putQueryParameter("RegionId", regionId);
	        request.putQueryParameter("TemplateCode", "SMS_204276056");

	        CommonResponse response = client.getCommonResponse(request);
	        System.out.println(response.getData());

	        String sendDate = DateUtil.format(DateUtil.DATE_PATTERN_1, new Date());
	        System.out.println(sendDate);
		} catch (ClientException e) {
			e.printStackTrace();
		}
	}

}
